"""错误处理和Qt环境设置"""

import sys
import os
from typing import List


def setup_qt_environment() -> None:
    """设置Qt运行时环境"""
    if hasattr(sys, '_MEIPASS'):
        # 打包环境下设置插件路径
        os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = os.path.join(
            sys._MEIPASS, 'PyQt6', 'Qt6', 'plugins', 'platforms'
        )
    
    # 设置高DPI支持
    if hasattr(sys, '_MEIPASS') or os.name == 'nt':
        os.environ["QT_ENABLE_HIGHDPI_SCALING"] = "1"
        os.environ["QT_SCALE_FACTOR"] = "1"
        os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1"


def check_qt_dependencies() -> List[str]:
    """检查Qt依赖是否完整"""
    missing_deps = []
    
    # 检查Qt核心库
    try:
        from PyQt6 import QtCore, QtGui, QtWidgets
    except ImportError as e:
        missing_deps.append(f"Qt核心库缺失: {e}")
    
    # 检查平台插件
    if sys.platform == 'win32':
        plugin_paths = [
            os.path.join(sys.prefix, 'Lib', 'site-packages', 'PyQt6', 'Qt6', 'plugins', 'platforms', 'qwindows.dll'),
            os.path.join(os.path.dirname(__file__), '..', '..', 'PyQt6', 'Qt6', 'plugins', 'platforms', 'qwindows.dll'),
        ]
        
        if hasattr(sys, '_MEIPASS'):
            plugin_paths.insert(0, os.path.join(sys._MEIPASS, 'PyQt6', 'Qt6', 'plugins', 'platforms', 'qwindows.dll'))
        
        plugin_found = any(os.path.exists(path) for path in plugin_paths)
        if not plugin_found:
            missing_deps.append("Qt平台插件缺失")
    
    return missing_deps


class TranscodeError(Exception):
    """转码错误基类"""
    pass


class FileError(TranscodeError):
    """文件错误"""
    
    def __init__(self, path: str, source_error: Exception):
        super().__init__(f"文件错误: {path}")
        self.path = path
        self.source_error = source_error


class GpuEncoderError(TranscodeError):
    """GPU编码器错误"""
    
    def __init__(self, gpu_type: str, source_error: Exception):
        super().__init__(f"GPU编码器错误: {gpu_type}")
        self.gpu_type = gpu_type
        self.source_error = source_error


class MemoryError(TranscodeError):
    """内存错误"""
    
    def __init__(self, required: int, available: int):
        super().__init__(f"内存不足: 需要 {required}MB, 可用 {available}MB")
        self.required = required
        self.available = available


def handle_error(error: Exception, context: str = "") -> None:
    """统一错误处理"""
    error_type = type(error).__name__
    error_message = str(error)
    
    print(f"错误 [{context}]: {error_type}: {error_message}")
    
    # 这里可以添加日志记录、用户通知等逻辑
    if isinstance(error, FileError):
        print(f"文件路径: {error.path}")
    elif isinstance(error, GpuEncoderError):
        print(f"GPU类型: {error.gpu_type}")
    elif isinstance(error, MemoryError):
        print(f"内存需求: {error.required}MB, 可用: {error.available}MB")


def safe_execute(func, *args, **kwargs):
    """安全执行函数，捕获并处理异常"""
    try:
        return func(*args, **kwargs)
    except Exception as e:
        handle_error(e, f"执行函数 {func.__name__}")
        return None